#include "ECadParser.h"

#include "CadHeaderParser.h"
#include "CadDataParser.h"
#include "QStringParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

ECadParser::ECadParser(
    QStringParser *&_nameParser
    , CadHeaderParser *&_cadHeaderParser
    , CadDataParser *&_cadDataParser
):    m_nameParser(_nameParser)
    , m_cadHeaderParser(_cadHeaderParser)
    , m_cadDataParser(_cadDataParser)
{

}

bool ECadParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new ECad());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("name")))
    {
        data = reader->attributes().value(QStringLiteral("name"));
        if (!m_nameParser->parse(reader, data))
            return false;
        m_result->name = m_nameParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("name: Attribute is required"));
        return false;
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
        if (name == QStringLiteral("CadHeader"))
        {
            if (!m_cadHeaderParser->parse(reader))
                return false;
            auto result = m_cadHeaderParser->result();
            m_result->cadHeader = result;
        }
        else if (name == QStringLiteral("CadData"))
        {
            if (!m_cadDataParser->parse(reader))
                return false;
            auto result = m_cadDataParser->result();
            m_result->cadData = result;
        }
        else
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

ECad *ECadParser::result()
{
    return m_result.take();
}

}